# -*- coding:utf-8 -*-
import os
import sys
import textwrap
import time

from livyOperator import livyOperator

__author__ = 'gin.chen'
__path__ = os.path.abspath(os.path.dirname(sys.argv[0])) + '/code_file.txt'
__livy_config_file = os.path.join(os.path.dirname(__file__), 'livy.config')



class Properties(object):
    def __init__(self, file_name):
        self.fileName = file_name
        self.properties = {}
        with open(self.fileName, 'r') as pro_file:
            for line in pro_file.readlines():
                line = line.strip().replace('\n', '')
                if line.find("#") != -1:
                    line = line[0:line.find('#')]
                if line.find('=') > 0:
                    strs = line.split('=')
                    strs[1] = line[len(strs[0]) + 1:]
                    self.properties[strs[0].strip()] = strs[1].strip()

    def get_properties(self):
        return self.properties

    def to_string(self):
        print(self.properties)


def get_livy_conn():
    config = Properties(__livy_config_file).get_properties()
    return livyOperator(host=config['livy.host'],
                        port=config['livy.port'],
                        kind=config['livy.kind'])


__livy_operator = get_livy_conn()


def session_execute_flow(data):
    livy_operator = __livy_operator
    if livy_operator.get_session():
        while 1:
            if livy_operator.check_session_idle():
                livy_operator.execute_session(data=data)
                break
            else:
                livy_operator.show_session()
                time.sleep(10)
    else:
        livy_operator.execute_session(data=data)

    while 1:
        if livy_operator.check_statements_finish():
            print(livy_operator.show_statements().get('output'))
            # livy_operator.delete_session()
            break
        else:
            livy_operator.show_statements()
            time.sleep(2)


def batch_execution_flow():
    __livy_operator.create_batches()
    while 1:
        state = __livy_operator.show_batches().get('state')
        if state == 'success':
            print('batch execute success!')
            break
        else:
            __livy_operator.show_batch_log()
            time.sleep(10)


def session_execute_by_file(path=__path__):
    try:
        with open(path, 'r') as f:
            session_execute_flow(textwrap.dedent(f.read()))
    except Exception as e:
        raise e

